import { KeyboardArrowDown as KeyboardArrowDownIcon, Check as CheckIcon } from '@mui/icons-material'
import { getShiftList, addAdvisorShift, editAdvisorShift } from '@/api'
import { ShiftItemCell, ShiftStatusCell } from '@/components/index'
import { ShiftStatus, DefaultPagination } from '@/store/constant'
import { DailyShift, ShiftItem, ShiftStatusItem } from '@/types/common'

interface Props {
  field: string
  value: DailyShift
  refresh: () => void
  row: any
}

const ITEM_HEIGHT = 48
const isPassed = (date: string) => dayjs(date).isBefore(dayjs(), 'day')

type OptionType = ShiftItem & ShiftStatusItem
const ScheduleActionButton = ({ field, value, row, refresh }: Props) => {
  // TODO:弃用组件内部的displayValue状态，采用更新rows显示修改后的内容
  const [displayValue, setDisplayValue] = useState(value || {})
  const { advisor_id } = row
  const { shift_id: originShiftId, status: originStatus, id } = value || {}
  const [anchorEl, setAnchorEl] = useState(null)
  const open = Boolean(anchorEl)
  const handleClick = (event: any) => {
    setAnchorEl(event.currentTarget)
  }
  const handleClose = () => {
    setAnchorEl(null)
  }

  // 修改【状态】或【排班】的判断条件
  const actionType = isPassed(field) && !isEmpty(value) ? 'status' : 'shift_id'

  const [params, setParams] = useState({
    size: DefaultPagination.pageSize,
    page: DefaultPagination.page + 1
  })
  const [selectedItem, setSelectedItem] = useState<OptionType | null>(null)
  const { data } = useRequest(() => getShiftList(params), {
    cacheKey: `/shift/list_${params.page}`,
    debounceWait: 500,
    refreshDeps: [params]
  })
  const list = (data?.data ?? []) as ShiftItem[]

  // 更新或者新增成功
  const onSuccess = () => {
    refresh()
    handleClose()
  }

  const { runAsync: addAsync, loading: addLoading } = useRequest(addAdvisorShift, {
    manual: true,
    onSuccess
  })
  const { runAsync: editAsync, loading: editLoading } = useRequest(editAdvisorShift, {
    manual: true,
    onSuccess
  })

  const handleMenuItemClick = (item: OptionType) => async () => {
    setSelectedItem(item)
    const shift_id = actionType === 'shift_id' ? item.shift_id : originShiftId
    const status = actionType === 'status' ? item.status : originStatus
    if (isEmpty(value)) {
      const data = {
        advisor_id,
        shift_id,
        date: field
      }
      await addAsync(data)
      setDisplayValue({ ...displayValue, shift_id })
    } else {
      const data = {
        shift_id,
        status,
        id
      }
      await editAsync(data)
      setDisplayValue({ ...displayValue, shift_id, status })
    }
  }

  useEffect(() => {
    setDisplayValue(value)
  }, [value])

  const changePage = (_e: any, page: number) => {
    const newParams = { ...params, page }
    setParams(newParams)
  }

  const iconItem = find(ShiftStatus, { status: displayValue?.status }) ?? {}
  const { icon: RenderIcon, color: iconColor } = iconItem
  return (
    <>
      <Box>
        <LoadingButton
          loading={addLoading || editLoading}
          color={isPassed(field) ? 'grey' : 'primary'}
          id="more-button"
          aria-controls={open ? 'more-menu' : undefined}
          aria-haspopup="true"
          aria-expanded={open ? 'true' : undefined}
          disableElevation
          onClick={handleClick}
          {...(isEmpty(value) && { endIcon: <KeyboardArrowDownIcon /> })}
        >
          {/* 显示排班状态 */}
          {(actionType === 'status' && originStatus) || (!originStatus && displayValue.status) ? (
            <RenderIcon color={iconColor[600]} />
          ) : (
            displayValue?.shift_id
          )}
        </LoadingButton>
        <Menu
          id="more-menu"
          MenuListProps={{
            'aria-labelledby': 'more-button'
          }}
          anchorEl={anchorEl}
          open={open}
          onClose={handleClose}
          PaperProps={{
            style: {
              maxHeight: ITEM_HEIGHT * 8,
              width: '30ch'
            }
          }}
        >
          <Grid container justifyContent="flex-end">
            <Pagination
              size="small"
              count={Math.ceil((data?.total ?? 0) / params.size)}
              variant="outlined"
              color="secondary"
              onChange={changePage}
            />
          </Grid>
          {actionType === 'shift_id'
            ? list.map((item: ShiftItem, index) => {
                return (
                  <MenuItem
                    key={index}
                    selected={item.shift_id === originShiftId}
                    onClick={handleMenuItemClick(item as OptionType)}
                  >
                    <ShiftItemCell index={index} item={item} />
                    {selectedItem?.shift_id === item.shift_id && <CheckIcon color="secondary" />}
                  </MenuItem>
                )
              })
            : ShiftStatus.map((item, index) => {
                return (
                  <MenuItem key={index} onClick={handleMenuItemClick(item as unknown as OptionType)}>
                    <ShiftStatusCell item={item} />
                    {selectedItem?.status === item.status && <CheckIcon color="secondary" />}
                  </MenuItem>
                )
              })}
        </Menu>
      </Box>
    </>
  )
}

export default ScheduleActionButton
